package com.ruifu.conversions.utils;

import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.StreamOpenOfficeDocumentConverter;
import com.ruifu.conversions.config.OpenOfficeConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.File;
import java.net.ConnectException;

/**
 * 持txt docx pptx xlsx doc xls ppt 转pdf
 * @author li176
 */
@Component
@Slf4j
public class Office4Pdf {
    @Autowired
    OpenOfficeConfig openOfficeConfig;
    public File Office2Pdf(File file){

        //判断源文件是否存在
        if (!file.exists()){
            throw new RuntimeException("源文件不存在!");
        }

        //输出文件
        File outputFile = new File(file.getName().substring(0,file.getName().lastIndexOf("."))+".pdf");

        //创建连接
        OpenOfficeConnection connection = new SocketOpenOfficeConnection(openOfficeConfig.getUrl(),openOfficeConfig.getPort());
        try {
            //远程连接OpenOffice服务
            connection.connect();
            //创建文件转换器
            DocumentConverter converter = new StreamOpenOfficeDocumentConverter(connection);
            //开始转换
            converter.convert(file, outputFile);
           if (outputFile.exists()){
               log.info(file.getName()+"文件转换成功");
           }else {
               log.info(file.getName()+"文件转换失败");
           }
        } catch (ConnectException e) {
            e.printStackTrace();
            log.info("OpenOffice服务启动失败");
        }
        return outputFile;
    }
}
